package com.bbm.communitysystem.controller;


import cn.hutool.core.bean.BeanUtil;
import com.bbm.communitysystem.core.domain.R;
import com.bbm.communitysystem.domain.Community;
import com.bbm.communitysystem.domain.Household;
import com.bbm.communitysystem.domain.Role;
import com.bbm.communitysystem.domain.UserInfo;
import com.bbm.communitysystem.domain.bo.UserInfoBo;
import com.bbm.communitysystem.domain.dto.FamilyDto;
import com.bbm.communitysystem.domain.dto.UserInfoDto;
import com.bbm.communitysystem.domain.vo.UserInfoPageVo;
import com.bbm.communitysystem.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bbm
 * @since 2025-02-13
 */
@Tag(name = "用户信息")
@Slf4j
@RestController
@RequestMapping("/userInfo")
@RequiredArgsConstructor
public class UserInfoController {

    private final IUserInfoService userInfoService;

    private final ICommunityService communityService;

    private final IHouseholdService householdService;

    private final IRoleService roleService;

    private final IFamilyService familyService;

    @Operation(summary = "修改用户头像")
    @PutMapping("/avatar")
    public R<String> putUserHeadImg(@RequestParam("img")MultipartFile file, @RequestParam("id") Integer userId) {

        UserInfoBo userInfoBo = new UserInfoBo();

        userInfoBo.setId(userId);
        userInfoBo.setUserImg(file);

        UserInfoDto userInfoDto = userInfoService.PutUserHeadImg(userInfoBo);

        if (userInfoDto == null) {
            return R.error("修改失败");
        }

        return R.ok("修改成功", userInfoDto.getUserImg());
    }

    @Operation(summary = "修改用户信息", description = "普通用户修改信息")
    @PutMapping("/info")
    public R putUserInfo(@RequestBody UserInfoDto userInfoDto) {
        log.info("信息：{}", userInfoDto);
        boolean update = userInfoService.
                lambdaUpdate()
                .set(!userInfoDto.getUserNick().isEmpty(), UserInfo::getUserNick, userInfoDto.getUserNick())
                .set(!userInfoDto.getUserEmail().isEmpty(), UserInfo::getUserEmail, userInfoDto.getUserEmail())
                .set(UserInfo::getUserSex, userInfoDto.getUserSex())
                .set(userInfoDto.getIsSun() != null, UserInfo::getIsSun, userInfoDto.getIsSun())
                .set(userInfoDto.getCommunityId() != null && userInfoDto.getCommunityId() != 0, UserInfo::getCommunityId, userInfoDto.getCommunityId())
                .set(UserInfo::getUpdateTime, System.currentTimeMillis() + "")
                .set(UserInfo::getUpdateBy, userInfoDto.getUpdateBy())
                .eq(UserInfo::getId, userInfoDto.getId())
                .update();

        if (!update) {
            return R.error("修改失败");
        }

        return R.ok("修改成功");
    }


    @Operation(summary = "获取用户头像")
    @GetMapping("/avatar/{id}")
    public R<String> getUserAvatar(@PathVariable("id") Integer id) {

        UserInfo byId = userInfoService.getById(id);

        if (byId == null) {
            return R.error("没有这个用户");
        }

        return R.ok("获取成功", byId.getUserImg());
    }

//    @Operation(summary = "获取用户信息,废弃 22日删除")
//    @GetMapping("/{id}")
//    public R getUserInfo(@PathVariable("id") Integer id) {
//
//        UserInfo byId = userInfoService.getById(id);
//        if (byId == null) {
//            return R.error("没有这个用户");
//        }
//        return R.ok(byId);
//    }


    @Operation(summary = "获取用户信息")
    @GetMapping("/home/{id}")
    public R<UserInfoPageVo> getHomeUserInfo(@PathVariable("id") Integer id) {

        UserInfo byId = userInfoService.getById(id);

        UserInfoPageVo userInfoPageVo = BeanUtil.copyProperties(byId, UserInfoPageVo.class);

        userInfoPageVo.setBirthDate(byId.getUserBirthDate());
        userInfoPageVo.setImg(byId.getUserImg());
        userInfoPageVo.setNick(byId.getUserNick());
        userInfoPageVo.setSex(byId.getUserSex());
        userInfoPageVo.setUserEmail(byId.getUserEmail());


        //目前没有角色系统
        String[] split = byId.getUserRoleId().split(",");
        String[] roleName = new String[split.length];
        userInfoPageVo.setRoleId(split);

        for (int i = 0; i < split.length; i++) {
            Role byId1 = roleService.getById(Integer.parseInt(split[i]));
            if (byId1 == null) {
                continue;
            }
            roleName[i] = byId1.getRoleName();
        }

        if (roleName.length == 0) {
            roleName = new String[]{"无"};
        }
        userInfoPageVo.setRoleName(roleName);

        Household one = householdService.lambdaQuery()
                .eq(Household::getUserId, id)
                .one();

        if (one == null) {
            one = createHousehold(byId);
        }

        if (one != null) {
            userInfoPageVo.setHouseholdId(one.getId());
            userInfoPageVo.setFamilyId(one.getFamilyId());
        }


        userInfoPageVo.setCommunityId(byId.getCommunityId());

        if (byId.getCommunityId() == null) {
            userInfoPageVo.setCommunityName("无");
            userInfoPageVo.setIsSun(byId.getIsSun() == 1);
            return R.ok("获取成功", userInfoPageVo);
        }

        Community byId1 = communityService.getById(byId.getCommunityId());

        if (byId1 == null) {
            return R.ok("获取成功", userInfoPageVo);
        }

        userInfoPageVo.setCommunityName(byId1.getCommunityName());

        userInfoPageVo.setIsSun(byId.getIsSun() == 1);




        return R.ok("获取成功", userInfoPageVo);
    }

    @Operation(summary = "获取用户列表, dev环境使用,无VO")
    @GetMapping("/list")
    public R getUserList() {
        return R.ok(userInfoService.list());
    }


    private Household createHousehold(UserInfo userInfo) {

        FamilyDto familyDto = new FamilyDto();
        familyDto.setFamilyName(userInfo.getUserNick() + "的家庭");
        familyDto.setUpdateBy(userInfo.getId() + "");

        FamilyDto family = familyService.createFamily(familyDto);

        Household household = new Household();
        household.setHouseholdName(userInfo.getUserNick());
        household.setUpdateTime(System.currentTimeMillis() + "");
        household.setUpdateBy(userInfo.getId() + "");
        household.setFamilyId(family.getId());
        household.setUserId(userInfo.getId());

        boolean save = householdService.save(household);



        return save ? household : null;
    }

}
